#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time: 2023/6/15 14:32
# @Author: Anthony (anthony66888@163.com)
# @description: 
"""
import time
import traceback
from urllib import parse
import requests
from auto_battle_room.utils.yaml_control import YamlControl

config_data = YamlControl("/data/config.yaml").read_yaml()  # 读取配置项
host = config_data["host"]  # 获取环境域名


def get_user_id(token):
    url = "/api/profile/userInfo"
    headers = {
        "Token": token
    }
    response = requests.get(url=host + url, headers=headers)
    return response.json()["data"]["id"]


def login(account, password):
    url = "/api/auth/login"
    data = {"id": account,
            "password": password,
            "type": 0
            }
    data = parse.urlencode(data)
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    return requests.post(url=host + url, data=data, headers=headers)


def init_login(account=None, player=None):
    """
    获取玩家列表并登陆、箱子列表，可输入可固定
    :param account: 登陆账号，为空时批量登陆，不为空时单个登陆
    :param player: 1=对战玩家 2=开箱玩家，为空时两者均登陆

    """
    yaml_control_user = YamlControl("/data/user_info.yaml")
    yaml_control_user_dream = YamlControl("/data/dream_user_info.yaml")

    # 单个登陆
    if account:
        try:
            token = login(account=account, password=account).json()["data"]  # 登陆获取新token
            if token is None:
                print(f"{account}登陆失败")
            else:
                print(f"{account}登陆成功,token:{token}")

                # 通过账号判断是对战玩家还是开箱玩家
                if account < 26111111300:  # 对战玩家
                    user_id = get_user_id(token)
                    yaml_control_user.update_key_yaml(father_key="user_info",
                                                      child_key="token", child_value=token,
                                                      condition_key="uid", condition_value=user_id)
                else:  # 开箱玩家
                    user_id = get_user_id(token)
                    yaml_control_user_dream.update_key_yaml(father_key="user_info1",
                                                            child_key="token", child_value=token,
                                                            condition_key="uid", condition_value=user_id)
                return token
        except Exception as e:
            print(f"{account}账号/密码错误:{e}")
            traceback.print_exc()

    # 批量登陆对战玩家和roll房玩家
    else:
        if player is None:
            user_info = []
            user_info1 = []
            for player in config_data["player"]:  # 所有对战玩家均登陆，并全部存储到token列表，保持登陆态
                response = login(account=str(player["account"]), password=str(player["password"]))
                if response.json()["status"] == 0:
                    token = response.json()["data"]
                    user_id = get_user_id(token)
                    user_info.append({"uid": user_id, "token": token, "account": player["account"]})
                    print(f"{player}对战用户登陆成功")
                else:
                    print(f"{player}对战用户账号/密码错误")
            yaml_control_user.write_yaml({"user_info": user_info})

            for player1 in config_data["player1"]:  # 所有roll房玩家均登陆，并全部存储到token列表，保持登陆态
                response = login(account=str(player1["account"]), password=str(player1["password"]))
                if response.json()["status"] == 0:
                    # time.sleep(2)
                    token = response.json()["data"]
                    user_id = get_user_id(token)
                    user_info1.append({"uid": user_id, "token": token, "account": player1["account"]})
                    print(f"{player1}开箱/追梦用户登陆成功")
                else:
                    print(f"{player1}开箱/追梦用户账号/密码错误")
            yaml_control_user_dream.write_yaml({"user_info1": user_info1})

        # 批量登陆对战玩家
        elif player == 1:
            yaml_control_user = YamlControl("/data/user_info.yaml")
            user_info = []
            for player in config_data["player"]:  # 所有对战玩家均登陆，并全部存储到token列表，保持登陆态
                response = login(account=str(player["account"]), password=str(player["password"]))
                if response.json()["status"] == 0:
                    token = response.json()["data"]
                    user_id = get_user_id(token)
                    user_info.append({"uid": user_id, "token": token, "account": player["account"]})
                    print(f"{player}对战用户登陆成功")
                else:
                    print(f"{player}对战用户账号/密码错误")
            yaml_control_user.write_yaml({"user_info": user_info})

        # 批量登陆roll房玩家
        else:
            yaml_control_user_dream = YamlControl("/data/dream_user_info.yaml")
            user_info1 = []
            for player1 in config_data["player1"]:  # 所有开箱玩家均登陆，并全部存储到token列表，保持登陆态
                response = login(account=str(player1["account"]), password=str(player1["password"]))
                if response.json()["status"] == 0:
                    token = response.json()["data"]
                    user_id = get_user_id(token)
                    user_info1.append({"uid": user_id, "token": token, "account": player1["account"]})
                    print(f"{player1}开箱/追梦用户登陆成功")
                else:
                    print(f"{player1}开箱/追梦用户账号/密码错误")
            yaml_control_user_dream.write_yaml({"user_info1": user_info1})
        return None


if __name__ == '__main__':
    init_login(player=2)
